﻿using System.Web;
using System.IO;

namespace N2.Web
{
	using Edit.Js;
	
	public abstract class DirectoryResourceHandler: DirectoryCompiler
	{
		string CurrentHandlerPath {
			get {
				return this.Context.Request.AppRelativeCurrentExecutionFilePath;
			}
		}

		protected virtual string BaseVirtualPath {
			get { return VirtualPathUtility.GetDirectory(this.CurrentHandlerPath); }
		}

		/// <summary>
		/// *.axd?set={name} => ./{name}
		/// </summary>
		/// <returns></returns>
		string GetSetNameFromQueryString()
		{
			return this.Context.Request["set"] as string;
		}

		/// <summary>
		/// {name}.axd => ./{name}
		/// </summary>
		/// <returns></returns>
		string GetSetNameFromBaseHandlerName()
		{
			var _path = this.CurrentHandlerPath;
			var _name = VirtualPathUtility.GetFileName(_path);
			var _ext = VirtualPathUtility.GetExtension(_path);
			return _name.Substring(0, _name.Length - _ext.Length);
		}

		public override string FolderUrl {
			get {
				var _basePath = VirtualPathUtility.AppendTrailingSlash(this.BaseVirtualPath);
				
				var _setName = this.GetSetNameFromQueryString() ?? this.GetSetNameFromBaseHandlerName();
				var _setPath = VirtualPathUtility.Combine(_basePath, _setName);

				return
					string.IsNullOrEmpty(_setName)
							|| !Directory.Exists(this.Context.Server.MapPath(_setPath))
						? _basePath
						: _setPath;
			}
		}
	}
}
